import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

class Solution3 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root ==null){
            return null;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> ret = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new LinkedList<>();
            while(size!=0){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                size--;
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            ret.add(list);
        }
        return ret;
    }
}